#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
using namespace std;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;    // 定义条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 定义全局锁

int tickets = 5000;

void *threadRoutine(void *args)
{
    string threadname = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            // 充当抢票花费的时间
            cout << threadname << ": get a ticket, ticket : " << tickets << endl;
            tickets--;
        }
        else
        {
            cout << threadname << "没有票了" << endl;
            //1.线程在等待的时候, 会自动释放锁
            //2.线程被唤醒的时候, 是在临界区内被唤醒的,当线程被唤醒,在wait函数返回时, 要重新申请并释放锁
            //3.当线程被唤醒的时候, 重新申请并持有所也是要参与锁的竞争的!
            pthread_cond_wait(&cond, &mutex); // 没有票了, 就去条件变量下等待
        }
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, threadRoutine, (void *)"thread-1");
    pthread_create(&t2, nullptr, threadRoutine, (void *)"thread-2");
    pthread_create(&t3, nullptr, threadRoutine, (void *)"thread-3");

    sleep(5); // 5s之后唤醒线程

    while (true)
    {

        sleep(6);
        pthread_mutex_lock(&mutex);
        tickets += 1000; // 每隔6s, 就再放1000张票
        pthread_mutex_unlock(&mutex);
        //pthread_cond_broadcast(&cond); // 唤醒所有线程
        pthread_cond_signal(&cond);    // 唤醒一个线程 

        pthread_join(t1, nullptr);
        pthread_join(t2, nullptr);
        pthread_join(t3, nullptr);
        return 0;
    }
}